package com.ccx.coachsite.versionupdate;



import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.ccx.coachsite.R;
import com.ccx.coachsite.api.CoachSiteSoftMgrApiAccessor;
import com.ccx.coachsite.model.ServerDetailResult;
import com.ccx.coachsite.model.SoftVersionUpdateItem;

/**
 * <br>Description:软件更新任务
 */
public class SoftUpdateTask extends AsyncTask<Object, Integer, String> {
	
	protected Context context = null;
	protected Handler handler = null;
	protected String  versionName="";
	private String version;
	private String url;
	private String content;
	
	private static final String SUCC_CODE = "200";
	/**
	 * 是否显示等待框
	 */
	private boolean isShowWaitingDialog = true;
	
	public SoftUpdateTask(Context ctx, boolean isShowWaitingDialog) {
		super();
		this.context = ctx;
		this.isShowWaitingDialog = isShowWaitingDialog;
	}

	public SoftUpdateTask(Context ctx, Handler handler, boolean isShowWaitingDialog) {
		super();
		this.context = ctx;
		this.handler = handler;
		this.isShowWaitingDialog = isShowWaitingDialog;
	}
	
    protected void onProgressUpdate(Integer... progress) {

    }
    
	@Override
	protected String doInBackground(Object... params) {
		try {
			PackageInfo packageinfo = context.getApplicationContext().getPackageManager().getPackageInfo(
					context.getApplicationContext().getPackageName(), PackageManager.GET_INSTRUMENTATION);
			versionName = packageinfo.versionName;
			
			ServerDetailResult<SoftVersionUpdateItem> serverDetailResult = CoachSiteSoftMgrApiAccessor.checkVersion();
			
			if ( !serverDetailResult.isbNetworkProblem() ) {
				version = serverDetailResult.detailItem.version;
				url = serverDetailResult.detailItem.url;
				content = serverDetailResult.detailItem.featureinfo;
			}
			
			return serverDetailResult.getResultCode()+"";
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	protected void onPostExecute(String result) {
		if(isShowWaitingDialog){
			WaitingView.cancelProgress();
		}
		if (SUCC_CODE.equals(result)) {
			
			//版本升级临时过渡 2012-11-19
			if ( "1.100".equals(version) ){
				
				if(handler != null){
					Message msg = handler.obtainMessage(ActionResult.ACTION_SUCCESS, false);
					msg.sendToTarget();
				}
				if(isShowWaitingDialog){
					Toast.makeText(context, R.string.soft_update_not_found_new_version, Toast.LENGTH_SHORT).show();
				}
				
				super.onPostExecute(result);
				
				return;
			}
			
			if ( SoftVersionUtils.isExistNewVersion(version, /*"1.9.1"*/versionName) ) {
				if(handler != null){
					Message msg = handler.obtainMessage(ActionResult.ACTION_SUCCESS, true);
					msg.sendToTarget();
				}
				if (isShowWaitingDialog) {
					Intent intent = new Intent(context,
							SoftUpdateDialog.class);
					Bundle bundle = new Bundle();
					bundle.putString("soft_url", url);
					bundle.putString("new_version", version);
					bundle.putString("content", content);
					intent.putExtras(bundle);
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent);
				} else {
					SharedPreferences sp = context.getSharedPreferences(SoftVersionUtils.VERSION_UPDATE_SETTING_NAME, Activity.MODE_PRIVATE);
					String notifyVersion = sp.getString("key_notify_version", versionName);//已经提醒过的的软件版本号
					if (!notifyVersion.equals(version)) {
						Intent intent = new Intent(context,
								SoftUpdateDialog.class);
						Bundle bundle = new Bundle();
						bundle.putString("soft_url", url);
						bundle.putString("new_version", version);
						bundle.putString("content", content);
						intent.putExtras(bundle);
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(intent);
						sp.edit().putString("key_notify_version",version).commit();
					} else {
						NotificationManager nManager = (NotificationManager) context.getSystemService(Service.NOTIFICATION_SERVICE);
						
						Notification notif = new Notification(R.drawable.icon, 
								context.getString(R.string.soft_update_notify_content, version), 
								System.currentTimeMillis());
						Intent mIntent = new Intent(context,SoftUpdateDialog.class);
						Bundle bundle = new Bundle();
						bundle.putString("soft_url", url);
						bundle.putString("new_version", version);
						bundle.putString("content", content);
						mIntent.putExtras(bundle);
						PendingIntent pIntent = PendingIntent.getActivity(context, 0, mIntent, 
								PendingIntent.FLAG_UPDATE_CURRENT);
						notif.flags = Notification.FLAG_AUTO_CANCEL;
				        notif.setLatestEventInfo(context, context.getResources().getString(R.string.main_bottom_app_name), 
				        		context.getString(R.string.soft_update_notify_content, version), pIntent);
				        nManager.notify(R.string.main_bottom_app_name, notif);
					}
				}
			} else {
				if(handler != null){
					Message msg = handler.obtainMessage(ActionResult.ACTION_SUCCESS, false);
					msg.sendToTarget();
				}
				if(isShowWaitingDialog){
					Toast.makeText(context, R.string.soft_update_not_found_new_version, Toast.LENGTH_SHORT).show();
				}
			}
		}else{
			if(handler != null){
				Message msg = handler.obtainMessage(ActionResult.ACTION_FAIL, false);
				msg.sendToTarget();
			}
			if(isShowWaitingDialog){
				Toast.makeText(context, R.string.soft_update_http_exception, Toast.LENGTH_SHORT).show();
			}
		}
		super.onPostExecute(result);
	}

	@Override
	protected void onPreExecute() {
		if(isShowWaitingDialog){
			WaitingView.showProgress(context, context.getResources().getString(R.string.soft_update_checking));
		}
		super.onPreExecute();
	}

}
